package rpc.frame.core.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import rpc.frame.core.data.RpcRequest;
import rpc.frame.core.util.ProtostuffUtil;

import java.nio.ByteBuffer;
import java.util.List;

/**
 * 反序列化 将字节数组转化成 系统可识别的对象
 * by xingRui 20230504
 */
@Slf4j
public class RpcRequestDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        try {
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            RpcRequest deserialize = ProtostuffUtil.deserialize(bytes, RpcRequest.class);
            list.add(deserialize);
        } catch (Exception e) {
            log.error("RpcRequestDecoder error msg={}",e);
            throw new RuntimeException(e);
        }
    }
}
